package com.tianquan.client.registry;

import com.tianquan.common.instance.ServiceInstance;
import lombok.extern.slf4j.Slf4j;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Author: tianquan
 * @date: 2024-11-03  10:39
 * @Description: 注册的服务实例
 */
@Slf4j
public class ClientInstanceManager {

    // 存储服务实例
    public static final Map<String, Set<ServiceInstance>> INSTANCES = new ConcurrentHashMap<>();

    // 删除实例
    public static void removeInstance(String serviceName, String id) {
        Set<ServiceInstance> serviceInstances = INSTANCES.get(serviceName);
        if (serviceInstances != null) {
            serviceInstances.removeIf(instance -> instance.getId().equals(id));
        }
    }

    // 注册实例
    public static void registerInstance(String serviceName, ServiceInstance instance) {
        log.info("注册实例: {}", instance);
        Set<ServiceInstance> serviceInstances = INSTANCES.get(serviceName);
        if (serviceInstances == null) {
            serviceInstances = new HashSet<>();
            serviceInstances.add(instance);
            INSTANCES.put(serviceName, serviceInstances);
        }
        serviceInstances.add(instance);
    }

    // 清空实例
    public static void clear() {
        INSTANCES.clear();
    }

    // 根据名称获取实例
    public static Set<ServiceInstance> getInstance(String serviceName) {
        return INSTANCES.get(serviceName);
    }

    // 获取所有实例
    public static Map<String, Set<ServiceInstance>> getInstances() {
        return INSTANCES;
    }

}
